﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace tlBasic.Application.File
{
    [ApiDescriptionSettings("文件管理")] 
    public class FileService : IDynamicApiController
    {

        private static string DiskPath = App.Configuration["FileConfig:DiskPath"];
        private static string FileOutUrl = App.Configuration["FileConfig:OutUrl"];
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>  
        [HttpPost]
        public async Task<dynamic> UploadFileAsync(IFormFile file)
        {
            if (file == null)
            {
                throw Oops.Bah("上传文件不能为空");
            }


            DateTime dt = DateTime.Now;
            var dicPath = $@"{dt.Year}/{dt.Month}/{dt.Day}/{YitIdHelper.NextId()}/";

            var savePath = Path.Combine(DiskPath, dicPath);
            var fileName = file.FileName;

            var linkPath = dicPath + fileName;
            var extension = Path.GetExtension(fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            TimeSpan useTime = new TimeSpan(DateTime.Now.Ticks - dt.Ticks);
            return new
            {
                Name = fileName,
                Url = linkPath,
                Extension = extension,
                UseTime = useTime
            };

        }
    }
}
